﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Mvvm;
using Mvvm.UI.Interactivity;
using LayoutPlanning.Model;
using LayoutPlanning.ViewModel;
using Toolbox.Extensions;
using Point = System.Windows.Point;

namespace LayoutPlanning.Behaviours
{
    public class DragBehavior : Behavior<FrameworkElement>
    {
        private bool _isRunning = false;
        private Point _mouseStartPosition;
        private static FrameworkElement current = null;

        private TaskFactory factory = new TaskFactory();

        protected override void OnDetaching()
        {
            base.OnDetaching();
        }

        protected override void OnAttached()
        {
            if (ViewModelBase.IsInDesignMode)
                return;

            var element = AssociatedObject;
            Panel parent = (ZoomableCanvas) element.FindAncestor(true, typeof (ZoomableCanvas));
            // = Application.Current.MainWindow;
            if (parent == null)
                parent = (Grid) element.FindAncestor(true, typeof (Grid));
            element.MouseWheel += (object sender, MouseWheelEventArgs e) =>
            {
                if ((AssociatedObject as FrameworkElement)?.DataContext is GraficalObject)
                {
                    var view = ((FrameworkElement) AssociatedObject).DataContext as GraficalObject;
                    if (e.RightButton == MouseButtonState.Pressed)
                        view.Angle += e.Delta/300;
                    else
                    {
                        view.Angle += e.Delta/10;
                        //view.Delta = e.Delta/10;
                    }
                    e.Handled = true;
                }
                else if ((AssociatedObject as FrameworkElement)?.DataContext is WorkPosition)
                {
                    var view = ((FrameworkElement) AssociatedObject).DataContext as WorkPosition;
                    if (e.RightButton == MouseButtonState.Pressed)
                        view.Angle += e.Delta/300;

                    else
                    {
                        view.Angle += e.Delta/10;
                        //view.Delta = e.Delta/10;
                    }
                    e.Handled = true;
                }
            };

            element.MouseLeftButtonDown += (sender, e) =>
            {
                if (current != null || (ViewModelLocator.Main.DrawNewSquare != DrawType.Nothing))
                    return;

                current = element;
                e.Handled = true;
                //_elementStartPosition = element.TranslatePoint(new Point(), parent);
                if (element is ZoomableCanvas)
                {
                    _mouseStartPosition = e.GetPosition(element);

                }
                else
                {
                    _mouseStartPosition = e.GetPosition(parent);
                }
                
                element.CaptureMouse();
            };

            element.MouseLeftButtonUp += (sender, e) =>
            {
                current = null;
                element.ReleaseMouseCapture();
                //if ((AssociatedObject as FrameworkElement)?.DataContext is Station)
                //{

                //    var view = ((FrameworkElement)AssociatedObject).DataContext as Station;
                //    ViewModelLocator.Main.SelectedGraficalObject = view;
                //    if (element.RenderTransform != null)
                //    {
                //        view.Position.X = element.RenderTransform.Value.OffsetX;
                //        view.Position.Y =  element.RenderTransform.Value.OffsetY;
                //        //element.RenderTransform = view.Transform;
                //        //view.RefreshPos();


                //    }
                //}
            };

            element.MouseMove += async (sender, e) =>
            {
                
                
                if (!_isRunning && current == element && ViewModelLocator.Main.DrawNewSquare == DrawType.Nothing)
                {
                    if (e.LeftButton == MouseButtonState.Pressed)
                    {
                        _isRunning = true;
                        
                        if (element is ZoomableCanvas)

                        { 
                            
                            var pos = e.GetPosition(element);
                            if (pos == _mouseStartPosition)
                            {
                                _isRunning = false;
                                return;
                            }
                            Vector dif = pos - _mouseStartPosition;

                            ViewModelLocator.Main.Offset.X -= dif.X * 0.061;
                            ViewModelLocator.Main.Offset.Y -= dif.Y * 0.061;
                            _mouseStartPosition = e.GetPosition(element);//pos;
                           // _mouseStartPosition.X -= dif.X * ViewModelLocator.Main.Zoom;
                            //_mouseStartPosition.Y -= dif.Y * ViewModelLocator.Main.Zoom;
                            _isRunning = false;
                            return;

                        }
                        await element.Dispatcher.InvokeAsync(() =>
                        {
                            
                            TranslateTransform transform =
                                (element.RenderTransform as TransformGroup)?.Children.FirstOrDefault(
                                    t => t is TranslateTransform) as TranslateTransform;

                            if (transform == null)
                            {
                                transform = element.RenderTransform as TranslateTransform;
                                if (transform == null)
                                    return;
                                var pos = e.GetPosition(parent);
                                Vector dif = pos - _mouseStartPosition;
                                transform.X += dif.X;
                                transform.Y += dif.Y;
                                return;
                            }

                            var ppos = e.GetPosition(parent);
                            Vector diff = ppos - _mouseStartPosition;
                            if (diff.Length == 0)
                                return;
                            if (element.IsMouseCaptured)
                            {
                                _mouseStartPosition = ppos;
                                if ((AssociatedObject as FrameworkElement)?.DataContext is ObservableDragableObject)
                                {
                                    var view =
                                        ((FrameworkElement) AssociatedObject).DataContext as ObservableDragableObject;
                                    if (element.RenderTransform != null && view != null)
                                    {
                                        var x = view.Position.X + diff.X;
                                        view.Position.X = x;
                                        var y = view.Position.Y + diff.Y;
                                        view.Position.Y = y;
                                    }
                                }

                                else
                                {
                                    transform.X += diff.X;
                                    transform.Y += diff.Y;
                                }
                            }
                        },
                            DispatcherPriority.Normal);
                        _isRunning = false;
                    }
                }
                else
                {
                }
            };
        }
    }
}